package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;
///system/dept/list.do
@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {


    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list",name = "分页展示部门列表数据")
    public String findAll(@RequestParam(value = "page",required=false,defaultValue ="1" )Integer pageNum,
                          @RequestParam(required=false,defaultValue ="10" )Integer pageSize){

//        分页查询部门数据时要区分是哪个企业的
        PageInfo pageInfo = deptService.findPage(getCompanyId(),pageNum,pageSize);
        request.setAttribute("page",pageInfo); //这个“page” 固定不能修改 因为页面上要的就是page这个变量名
        return "system/dept/dept-list";
    }
    @RequestMapping(value = "/toAdd",name = "进入到新增部门的页面")
    public String toAdd(){
//        查询当前企业的所有部门数据
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);

        return "system/dept/dept-add";
    }


    @RequestMapping(value = "/edit",name = "保存部门的方法")
    public String edit(Dept dept){

        if(dept.getParent().getId().equals("")){
            dept.getParent().setId(null);
        }

//        判断dept中id是否为空，如果为空就是新增反之就是修改
        if(StringUtils.isEmpty(dept.getId())){//如果为空
            String id = UUID.randomUUID().toString();
            dept.setId(id);
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept);
        }else{
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do"; //一定要重定向到列表页面
    }

    @RequestMapping(value = "/toUpdate",name = "进入到修改部门的页面")
    public String toUpdate(String id){
        Dept dept = deptService.findById(id);
        request.setAttribute("dept",dept);

        //        查询当前企业的所有部门数据
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);

        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/delete",name = "删除部门的方法")
    public String delete(String id){
        deptService.delete(id);
        return "redirect:/system/dept/list.do"; //一定要重定向到列表页面
    }

}
